package com.yzq.modular.demo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzq.modular.core.CacheOperatorApi;
import com.yzq.modular.core.CommonService;
import com.yzq.modular.core.PageInfo;
import com.yzq.modular.demo.entity.NewTest;
import com.yzq.modular.demo.entity.OldTest;
import com.yzq.modular.demo.service.NewTestService;
import com.yzq.modular.demo.service.OldTestService;
import com.yzq.modular.demo.service.TestTranslationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: modular
 * @Author: yzq
 * @Description: 新老数据转换处理服务类
 * @Date: 2022/4/18 14:03
 */
@Service
@Slf4j
public class TestTranslationServiceImpl extends CommonService<OldTest> implements TestTranslationService {
   // 缓存资源
    @Resource(name="pageInfoCache")
    private CacheOperatorApi<PageInfo> pageInfoCacheOperatorApi;
    // 每次分页处理的条数
    private final static int PAGE_SIZE = 250;
    // redis缓存名称
    private final static String TABLE_NAME = "login";
    @Resource
    private OldTestService oldTestService;
    @Resource
    private NewTestService newTestService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Override
    public PageInfo getPageInfo() {
        // 查看缓存有没有之前同步记录，有：从之前位置继续同步，没有：从头同步
        PageInfo pageInfo =this.getCahe(TABLE_NAME);
        if(ObjectUtil.isNotEmpty(pageInfo)){
            log.info("find tableName:{} pageCache, info:总数：{}，单页条数：{}，页数：{}，当前分页：{} "
                    ,TABLE_NAME,pageInfo.getTotal(),pageInfo.getPageSize(),pageInfo.getPageNum(),pageInfo.getCurrentPageNum());
            // 判断表有没有完成数据同步：redis的当前页是不是比总数据页大
            if(pageInfo.getCurrentPageNum()>pageInfo.getPageNum()){
                //完成同步的数据，不再继续运行
                log.info("old-database 表{} is complate when {}",TABLE_NAME,pageInfo.getDate());
                return null;
            }
            return pageInfo;
        }

        // 缓存无数据，读取数据库
        int total = oldTestService.getTableTotal();
        int pageNum = total%PAGE_SIZE==0?total/PAGE_SIZE:total/PAGE_SIZE+1;

        pageInfo = new PageInfo(PAGE_SIZE,
                pageNum,
                1,
                total,
                TABLE_NAME,
                new Date());
        return pageInfo;
    }

    @Override
    public void setCache(PageInfo pageInfo) {
        pageInfoCacheOperatorApi.put(TABLE_NAME,pageInfo);
    }

    @Override
    public PageInfo getCahe(String tableName) {
        return pageInfoCacheOperatorApi.get(tableName);
    }

    @Override
    public void complateCache(PageInfo currentPageInfo) {
        currentPageInfo.setCurrentPageNum(currentPageInfo.getPageNum()+1);
        currentPageInfo.setDate(new Date());

        pageInfoCacheOperatorApi.put(TABLE_NAME,currentPageInfo);
    }

    @Override
    public List<OldTest> getOldInfo(PageInfo pageInfo) {
        // 获取旧表数据
        Page<OldTest> oldTestPage = new Page<>();
        oldTestPage.setSize(pageInfo.getPageSize());
        oldTestPage.setCurrent(pageInfo.getCurrentPageNum());
        Page<OldTest> loginPage1= oldTestService.page(oldTestPage);
        List<OldTest> list = new ArrayList<>();
        if(ObjectUtil.isNotEmpty(loginPage1)){
            list =oldTestPage.getRecords();
        }
        return list;

    }

    @Override
    public void translate(List<OldTest> list) {
        List<NewTest> newTestList = new ArrayList<>();

        /*
        *
        * 新旧表的数据转换在此处理
        *
        *
        * */
        //Date now = new Date();
        // 遍历旧表数据
        for(OldTest oldTest:list){
            NewTest studyNewTest = new NewTest();
            NewTest projectNewTest = new NewTest();
            NewTest recommendNewTest= new NewTest();

            // 用户id
            studyNewTest.setUserId(oldTest.getUserId());
            projectNewTest.setUserId(oldTest.getUserId());
            recommendNewTest.setUserId(oldTest.getUserId());

            // 学习积分
            studyNewTest.setIntegralType(1);
            studyNewTest.setIntegralValue(oldTest.getStudyIntegral());

            // 项目积分
            projectNewTest.setIntegralType(2);
            projectNewTest.setIntegralValue(oldTest.getProjectIntegral());

            // 推荐积分
            recommendNewTest.setIntegralType(3);
            recommendNewTest.setIntegralValue(oldTest.getRecommendIntegral());

            // 创建时间
            Date createTime = new Date();
            if(ObjectUtil.isNotEmpty(oldTest.getCreateTime())){
                createTime = new Date(oldTest.getCreateTime()*1000);
            }
            studyNewTest.setCreateTime(createTime);
            projectNewTest.setCreateTime(createTime);
            recommendNewTest.setCreateTime(createTime);

            newTestList.add(studyNewTest);
            newTestList.add(projectNewTest);
            newTestList.add(recommendNewTest);
        }

        transactionTemplate.execute(action->{
            newTestService.saveBatch(newTestList);
            return new Object();
        });
        log.info("oldtest 完成数据同步 id 列表：{}", JSON.toJSONString(list.stream().map(OldTest::getId).collect(Collectors.toList())));

    }

    @Override
    public void translation() {
        this.template();
    }
}
